package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @program: gulimall
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-07-16 11:09
 **/
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;


    //根据token获取用户信息
    @ResponseBody
    @GetMapping("/userInfo")
    public String userinfo(@RequestParam(value = "token") String token) {
        return redisTemplate.opsForValue().get(token);
    }


    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
                            Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token) {

        String token = redisTemplate.opsForValue().get("token");
        //这里从redis中获取token,然后比较两个token是否相同
        if (token!=null && token.equals(sso_token)){
            //token验证成功,直接返回
            return "redirect:"+url+"?token="+token;
        }

        model.addAttribute("url", url);
        return "login";
    }


    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {

        //简单演示登录成功
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //保存登录状态
            String token = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(token, username+"<-->"+password);
            redisTemplate.opsForValue().set("token", token);

            //任何一个客户端过来登录过,那么当前服务器就需要留一个记号,表示已经登录
            Cookie cookie = new Cookie("sso_token", token);
            response.addCookie(cookie);

            System.out.println("准备跳转!");
            //登录成功就跳转回之前的页面,并且给一个token给它
            return "redirect:"+url+"?token="+token;
        }else {


            return "login";
        }
    }


}
